-----------------------------------------------------------------------------
-- 羁绊主界面
--
---------------
-- Author: wd
-----------------------------------------------------------------------------
require 'Common/define'
require 'Logic/Config'
require 'Common/functions'

UIFetter = {};
HelperFunc.SetUIEnv(UIFetter)
local this = UIFetter;

this.hasInit = false;
this.btnBack = nil
this.btnAward = nil
this.btnAttr = nil
this.selectType = 0; --当前选中页签

this.crystalConfig = nil;
this.createCharactorConfig = nil;
this.heroConfig = nil;
this.heroRankConfig = nil;
this.heroMaxLevel =0;
this.g_SchooltTypeCount = 6
this.g_HeroCgs ={} --常规英雄信息
this.g_AllHeroCgs ={}
this.gameObjectName = nil
this.dynamicList = nil
this.tabList = nil
this.heroCgs = {}
this.objectName = nil
this.btnTip = nil;
function UIFetter.Init()
    if crystalConfig == nil then
        crystalConfig =G.dataTable["t_crystal"];
    end
    if createCharactorConfig == nil then
        createCharactorConfig =G.dataTable["t_createCharacter"];
    end
    if heroConfig == nil then
        heroConfig =G.dataTable["t_hero"];
    end
    if heroRankConfig == nil then
        heroRankConfig =G.dataTable["t_herorank"]
    end
    if heroMaxLevel ==0 then
        local heroExpConfig = G.dataTable["t_characterexp"];
        for _, value in pairs(heroExpConfig) do
            if value.f_CharacterLevel > heroMaxLevel then
                heroMaxLevel =  value.f_CharacterLevel;
            end
        end
    end
    selectType = EnumConst.HeroTypeEnum.HeroTypeAll
    this.ParseCollectionInfo()

    local name, packageName = getUIName(PanelResNames.UIFetter);
    panelMgr:ShowUI(name, packageName, this.OnCreate, Config.useLocalUI);
end

function UIFetter.OnCreate(obj)
    AddUIPackageDepend(PanelResNames.UIFetter,"FUI/SmallBodyAtlas")
    gameObjectName = obj.gameObjectName
    if not hasInit then
        hasInit = true;
        objectName = obj.gameObjectName

        btnBack = obj:GetChild("btnClose")
        btnAward = obj:GetChild("btnAward")
        btnAward.gameObjectName = "btnAward";
        btnAttr = obj:GetChild("btnAttr")
        dynamicList = obj:GetChild("HeroGroup")
        tabList = obj:GetChild("Tab")
        btnTip = obj:GetChild("n18")

        this.addEvent()
    end
    tabList.itemRenderer = this.UpdateTab;
    tabList.numItems = tabList.numItems

    this.InitSchoolTab()
end

function UIFetter.UpdateTab(index, obj)
    obj.onClick:Add(function()
        this.SelectSchoolTab(index, obj)
    end)
end

--- 初始化职业标签状态
function UIFetter.InitSchoolTab()
    for k = 1, tabList.numItems do
        local obj = tabList:GetChildAt(k-1)
        local ctrShow = obj:GetController("button")
        ctrShow.selectedIndex = 0
    end
    this.SelectSchoolTab(selectType, tabList:GetChildAt(0))
end

--- 职业标签选择
function UIFetter.SelectSchoolTab(index, obj)
    local lastObj = tabList:GetChildAt(selectType)
    local lastCtr = lastObj:GetController("button")
    lastCtr.selectedIndex = 0

    local ctrShow = obj:GetController("button")
    ctrShow.selectedIndex = 3
    selectType = index

    this.refreshPage()
end

function UIFetter.addEvent()
    btnBack.onClick:Add(this.onClickBack)
    btnAward.onClick:Add(this.onClickAward)
    btnAttr.onClick:Add(this.onClickAttr)
    btnTip.onClick:Add(this.ShowTips);
    UIRedDots.addViewListen(PanelNames.UIFetter,gameObjectName..btnAward.gameObjectName,btnAward,Config.RedDotsType.HeroFetterReward);
end

function UIFetter.removeEvent()
    btnBack.onClick:Clear()
    btnAward.onClick:Clear()
    btnAttr.onChanged:Clear()
    btnTip.onClick:Clear();
    UIRedDots.removeViewEvent(PanelNames.UIFetter)
end

function UIFetter.LocalListenEvent()

end

function UIFetter.LocalCloseEvent()

end

function UIFetter.OnDestroy()
    hasInit = false
    this.removeEvent();

    if UIPackage.GetById("FUI/SmallBodyAtlas") then
        UIPackage.RemovePackage("FUI/SmallBodyAtlas")
    end
end

function UIFetter.OnEnable()
    this.LocalListenEvent();
end

function UIFetter.OnDisable()
    this.LocalCloseEvent();
end

function UIFetter.ShowTips()
    local txts = {};
    txts["title"] = "HelpTitle4";
    txts["des"] = "HelpDes4";
    showUI(PanelNames.CommonTips,txts);
end

local PARAM_SORT_1 = 1
local PARAM_SORT_2 = 0
function UIFetter.ParseCollectionInfo()
    g_HeroCgs ={}
    g_AllHeroCgs = {}
    for schoolType = 1, g_SchooltTypeCount do
        for _, cfgInfo in pairs(heroConfig) do
            if cfgInfo.f_Type ~=2 and cfgInfo.f_Type ~= 3 then
                if cfgInfo.f_HeroType == schoolType and logicMgr.HeroManager.IsHeroByModelId(cfgInfo.f_HeroID) then

                    local heroData = {};
                    logicMgr.HeroManager.copyHeroConfig(cfgInfo, heroData)

                    if g_HeroCgs[schoolType] == nil then
                        g_HeroCgs[schoolType] = {}
                    end

                    local fellowInfo = logicMgr.HeroManager.getHeroDatabyModelId(cfgInfo["f_HeroID"],true)
                    if fellowInfo then
                        heroData["star"] = fellowInfo["star"]
                    end

                    if logicMgr.HeroManager.getHandbookByModelId(tostring(heroData.partnerModelId),true) then
                        heroData["_sortValue"] = PARAM_SORT_1
                    else
                        heroData["_sortValue"] = PARAM_SORT_2
                    end

                    table.insert(g_HeroCgs[schoolType], heroData)
                    table.insert(g_AllHeroCgs, heroData)

                end
            end
        end
    end
end

--英雄排序
function UIFetter.sortHero(a,b)
    if a.star > b.star then
        return true;
    else
        if a.star == b.star then
            return toNumber(a.partnerModelId) < toNumber(b.partnerModelId)
        else
            return false
        end
    end
end

function UIFetter.refreshPage()
    heroCgs = {}

    if selectType == EnumConst.HeroTypeEnum.HeroTypeAll then
        heroCgs = g_AllHeroCgs
    else
        if g_HeroCgs and g_HeroCgs[selectType] then
            heroCgs = g_HeroCgs[selectType]
        end
    end
    table.sort(heroCgs, this.sortHero)
    dynamicList.itemRenderer = this.refresHeroPosData
    dynamicList.numItems = #heroCgs
end

function UIFetter.refresHeroPosData(index, itemobj)
    index = index + 1
    local info = heroCgs[index]
    local img_Icon = itemobj:GetChild("HeroStand")
    local txtName = itemobj:GetChild("Title")
    local str = EnumConst.AtlasPath.SmallBodyAtlas..info.smallIcon;
    img_Icon.url = str
    txtName.text = info.name

    -- 灰态
    local ctrlGray = itemobj:GetController("c1")
    ctrlGray.selectedIndex = 0
    if logicMgr.HeroManager.getHandbookByModelId(tostring(info.partnerModelId),true) == nil then
        ctrlGray.selectedIndex = 1
    end

    -- 星级显示
    local heroStar = info["star"]/10;
    local StarPanel = itemobj:GetChild("StarList")
    local childCount = StarPanel.numItems;
    for i = 0,childCount-1 do
        ---@type FairyGUI.GComponent
        local child = StarPanel:GetChildAt(childCount-i-1)
        local ctl = child:GetController("cstar")
        if i < heroStar  then
            ctl:SetSelectedIndex(1)
        else
            ctl:SetSelectedIndex(0)
            break
        end
    end

    -- 事件侦听
    itemobj.onClick:Clear()
    itemobj.onClick:Add(function()
        this.onClickHeroPos(info.partnerModelId)
    end)

    -- 小红点
    local redStrFlag = objectName..itemobj.gameObjectName..index
    UIRedDots.removeListen(redStrFlag, Config.RedDotsType.OneHeroFetter);
    UIRedDots.addViewListen(PanelNames.UIFetter,redStrFlag, itemobj, Config.RedDotsType.OneHeroFetter, info.partnerModelId);
end

function UIFetter.onClickHeroPos(heroID)
    showUI(PanelNames.UIFetterDetial, heroID);
end

function UIFetter.onClickBack()
    closeUI(PanelNames.UIFetter);
end

function UIFetter.onClickAttr()
    showUI(PanelNames.UIFetterInfluence)
end

function UIFetter.onClickAward()
    showUI(PanelNames.UIFetterAward)
end

return UIFetter;
